<template>
  <div class="login-model">
    <header class="header tc f18">用户登录</header>
    <el-form class="form-container" label-width="80px" label-position="right" :model="form">
      <el-form-item label="用户名:">
        <el-input type="text" v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="密码:">
        <el-input type="password" v-model="form.pwd" @keydown.enter="login"></el-input>
      </el-form-item>
      <el-form-item>
        <label class="tip tl" v-if="error">用户名或密码错误.</label>
        <footer class="tr">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="success" plain @click="register">注册</el-button>
        </footer>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { reactive, ref } from "vue";
import request from "../request/index";
import store from "store/index";
export default {
  name: 'login',
  setup () {
    const error = ref(false);
    const form = reactive({
      name: '',
      pwd: '',
    })

    const login = (e) => {
      e.preventDefault();
      error.value = false;
      request.post('/user/login', form).then(resp => {
        if (resp && resp.data && resp.data.valid)        {
          store.commit('user/loginStatus', resp.data.valid);
          store.commit('user/setUser', resp.data)
          window.location.href = `${window.location.origin}/main.html?#/`
        } else        {
          store.commit('user/loginStatus', false);
          store.commit('user/setUser', null)
          error.value = true;
        }
      });
    }
    const register = () => {

    }

    return {
      error,
      form,
      login,
      register,
    }
  }
}
</script>

<style lang="scss" scoped >
.tip {
  color: red;
}
</style>